package medium;


public class T2 {
    public static void main(String[] args) {
        T2 t2 = new T2();
        System.out.println(t2.longestPalindrome("abccbac"));
    }

    public String longestPalindrome(String s) {
        if (s == null || s.length() < 2) {   
            return s;
        }

        int start = 0, maxLen = 1;
        for (int i = 0; i < s.length() - 1; i++) {
            // 奇数长度的回文子串
            int len1 = expandAroundCenter(s, i, i);
            // 偶数长度的回文子串
            int len2 = expandAroundCenter(s, i, i + 1);
            // 保留较长的回文子串
            int len = Math.max(len1, len2);
            if (len > maxLen) {
                start = i - (len - 1) / 2;
                maxLen = len;
            }
        }

        return s.substring(start, start + maxLen);
    }

    // 中心扩展法
    private int expandAroundCenter(String s, int left, int right) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        // 注意：这里返回的是长度，因此right要减去left（因为已经越界了）并加1
        return right - left - 1;
    }
}
